#include "Renderer.h"

#include <map>
#include <string>

#include <opencv/cv.h>
#include <opencv/highgui.h>

using namespace std;

Renderer::Renderer(int width, int height, int alpha, int beta) {
    this->width = width;
    this->height = height;
    this->alpha = alpha;
    this->beta = beta;
}

void Renderer::drawBound(Node* raiz, map<Node*, int> *id, CvFont* font, IplImage* image, int posX, int posY) {
    if(raiz->getType() == BISS) {
        if(raiz->getOrientation() == HORIZONTAL) {
            drawBound(raiz->getLeft(), id, font, image, posX, posY);
            drawBound(raiz->getRight(), id, font, image, posX, posY + raiz->getLeft()->getHeight(alpha, beta) + alpha);
        } else {
            drawBound(raiz->getLeft(), id, font, image, posX, posY);
            drawBound(raiz->getRight(), id, font, image, posX + raiz->getLeft()->getWidth(alpha, beta) + alpha, posY);
        }
    } else {
        cvRectangle(image, cvPoint(posX+beta, posY+beta), cvPoint(posX + raiz->getImage()->getWidth() - beta, posY + raiz->getImage()->getHeight() - beta), cvScalar(255,0,0));
        string sid;
        stringstream sstream;
        sstream << id->at(raiz) << " [" << raiz->getImage()->getRelativeArea() << "]";
        sid = sstream.str();
        cvPutText(image, sid.c_str(), cvPoint(posX + raiz->getImage()->getWidth()/2.0, posY + raiz->getImage()->getHeight()/2.0), font, cvScalar(255, 0, 0));
    }
}

IplImage* Renderer::drawImage(Node* raiz, map<Node*, int> *id) {
    IplImage* image = cvCreateImage(cvSize(width + width / 2.0, height + height / 2.0), IPL_DEPTH_8U, 3);
    CvFont font;
    cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 1.0f, 1.0f);
    cvRectangle(image, cvPoint(0, 0), cvPoint(width, height), cvScalar(0,150,0));
    cvRectangle(image, cvPoint(0, 0), cvPoint(raiz->getWidth(alpha, beta), raiz->getHeight(alpha, beta)), cvScalar(0,0,150));
    drawBound(raiz, id, &font, image, 1, 1);
    return image;
}
